import { promises } from "fs";
import fsextra from "fs-extra";
import path from "path";
import { minifyhtml } from "./minifyhtml";

export async function savepagedatajs(
    url: string,
    pagepath: string,
    cachetoc: Map<string, string>,
    cachetitle: Map<string, string>
) {
    const key = url;
    //@ts-ignore
    let filename = btoa(key) + ".js";
    let mdfilepath = path.join(pagepath, filename);

    const toc = cachetoc.get(url);
    const title = cachetitle.get(url);
    if (!toc) {
        throw new Error("toc not found");
    }
    if (!title) {
        throw new Error("title not found");
    }
    const tocmini =
        process.env.NODE_ENV === "development" ? toc : await minifyhtml(toc);
    const serilizedtext = [
        `import './${btoa(key)}.css'`,
        `import markdown from './${btoa(key)}.html'`,
        `export const url=${JSON.stringify(key)};`,
        `export {markdown}`,
        `export const toc=${JSON.stringify(tocmini)}`,
        `export const title=${JSON.stringify(title)}`,
    ].join("\n");

    await fsextra.ensureFile(mdfilepath);
    await promises.writeFile(mdfilepath, serilizedtext);
}
